package com.blog.back.config;

import com.blog.back.service.ArticleService;
import com.blog.entity.ArticleEntity;
import com.blog.exception.RRException;
import com.blog.vo.ArticleHelperVO;
import com.blog.vo.ArticleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * @author codeDorado
 * @version 1.0
 * @date 2020/8/18 10:29
 */
@Component
public class CacheArticleLinkedList {

    private static final CopyOnWriteArrayList<ArticleHelperVO> CacheList;

    public static CopyOnWriteArrayList<ArticleHelperVO> getCacheList() {
        return CacheList;
    }

    @Autowired
    ArticleService articleService;

    static {
        CacheList = new CopyOnWriteArrayList<>();
    }

    /**
     * 初始化缓存 list
     */
    @PostConstruct
    public void init() {
        List<ArticleEntity> list = articleService.list();
        System.out.println("我执行了");
        List<ArticleHelperVO> collect = list.stream()
                .map(enrty -> new ArticleHelperVO(enrty.getArticleId(), enrty.getArticleTitle()))
                .collect(Collectors.toList());
        CacheList.addAll(collect);
    }

    /**
     * 添加一个
     * @param articleHelperVO
     * @return
     */
    public static boolean add(ArticleHelperVO articleHelperVO) {
        CacheList.add(0, articleHelperVO);
        return true;
    }

    public static synchronized void remove(ArticleHelperVO articleHelperVO) {
        int index = getIndex(articleHelperVO);
        if (index == -1) throw new RRException("删除失败");
        CacheList.remove(index);
    }

    public static List<ArticleHelperVO> getPreAndNext(Long id) {
        ArticleHelperVO pre = null;
        ArticleHelperVO next = null;

        Iterator<ArticleHelperVO> iterator = CacheList.iterator();
        while (iterator.hasNext()) {
            ArticleHelperVO curr = iterator.next();
            if (curr.getArticleId().equals(id)) {
                if (iterator.hasNext()) next = iterator.next();
                break;
            }
            pre = curr;
        }
        return Arrays.asList(pre, next);
    }

    private static int getIndex(ArticleHelperVO articleHelperVO) {
        if (articleHelperVO == null) return -1;
        for (int i = 0; i < CacheList.size(); i++) {
            if (CacheList.get(i).getArticleId().equals(articleHelperVO.getArticleId()))
                return i;
        }
        return -1;
    }
}
